package com.thread.jucTest;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @program: leetcode
 * @description:
 * @author: wangzhihua
 * @date: 2024-06-22
 */
public class ReadWriteLockTest {

	@Test
	public void test1() {
		MyCache myCache = new MyCache();
		for (int i = 0; i < 5; i++) {
			final int num = i;
			new Thread(() -> {
				myCache.put(num, num);
			}, String.valueOf(i)).start();
		}
		for (int i = 0; i < 5; i++) {
			final int num = i;
			new Thread(() -> {
				myCache.get(num);
			}, String.valueOf(i)).start();
		}
		try {
			Thread.sleep(20000);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

class MyCache {
	private volatile Map<Object, Object> map = new HashMap<>();

	private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

	public Object get(Object key) {
		try {
			rwLock.readLock().lock();
			System.out.println(Thread.currentThread().getName() + " 正在读操作");
			Thread.sleep(300);
			Object value = map.get(key);
			System.out.println(Thread.currentThread().getName() + " 读完了");
			return value;
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			rwLock.readLock().unlock();
		}
		return null;
	}

	public void put(Object key, Object value) {
		try {
			rwLock.writeLock().lock();
			System.out.println(Thread.currentThread().getName() + " 正在写操作");
			Thread.sleep(300);
			map.put(key, value);
			System.out.println(Thread.currentThread().getName() + " 写完了");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			rwLock.writeLock().unlock();
		}
	}
}